/**
 * 
 */
package com.socialnetwork.user.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.socialnetwork.security.auth.AuthException;
import com.socialnetwork.security.auth.Authenticator;
import com.socialnetwork.user.model.User;
import com.socialnetwork.user.service.UserService;
import com.socialnetwork.user.util.WebConstants;

/**
 * @author asoundar
 * 
 */
@Controller
public class Login {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginPage() {
		return new ModelAndView("user/login");
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@ModelAttribute("user") User user,
			BindingResult result, SessionStatus status,
			HttpServletRequest request, HttpServletResponse response) {

		try {
			login(request, response, user.getEmail(), user.getPassword(), false);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/index";
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response) {

		HttpSession session = request.getSession();
		try {
			session.invalidate();
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/login";
	}

	private void login(HttpServletRequest request,
			HttpServletResponse response, String email, String password,
			boolean rememberMe) throws Exception {

		HttpSession session = request.getSession();

		int authResult = Authenticator.FAILURE;

		authResult = userService.authenticateByEmailAddress(email, password);

		if (authResult != Authenticator.SUCCESS) {
			throw new AuthException();
		}

		User user = userService.getUser(email);

		String userIdString = String.valueOf(user.getId());

		session.setAttribute("j_username", userIdString);
		session.setAttribute("j_password", user.getPassword());

		session.setAttribute(WebConstants.USER_ID, user.getId());
		session.setAttribute(WebConstants.USER, user);

	}
}
